<template>
  <AFormItemRest>
    <UserTable
      :column-selected="[
        'index',
        'userId',
        'userName',
        'nickName',
        'email',
        'phoneNumber',
        'statusName',
        'createTime',
        'action'
      ]"
      :data-source="sourceData"
      :row-selection="{ selectedRowKeys, onChange: setSelectedRowKeys }"
      :pagination="{
        simple: true,
        current: pagination.pageNum,
        pageSize: pagination.pageSize,
        total: selectedRowKeys.length,
        onChange: (pageNum, pageSize) => setPagination({ pageNum, pageSize })
      }"
      :searchEnable="false"
    >
      <template #operateLeft>
        <AButton type="primary" ghost :icon="createVNode(PlusOutlined)" @click="() => setOpenModal(true)">添加</AButton>
        <APopconfirm
          title="您确定批量取消选择数据吗?"
          ok-text="是"
          cancel-text="否"
          @confirm="() => onCancel(selectedRowKeys)"
        >
          <AButton danger ghost :icon="createVNode(DeleteOutlined)" :disabled="!selectedRowKeys.length">删除</AButton>
        </APopconfirm>
      </template>
      <template #bodyActionCell="{ record }">
        <APopconfirm
          title="您确定取消选择该数据吗?"
          ok-text="是"
          cancel-text="否"
          @confirm="() => onCancel([record.userId])"
        >
          <AButton type="link" danger size="small" :icon="createVNode(DeleteOutlined)">取消</AButton>
        </APopconfirm>
      </template>
    </UserTable>

    <SelectUserPanel
      :open="openModal"
      :api="() => props.api({ excludes: toValue(value) })"
      @finish="onSelectFinish"
      @cancel="() => setOpenModal(false)"
    >
    </SelectUserPanel>
  </AFormItemRest>
</template>

<script setup>
import { createVNode, toValue } from 'vue';
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons-vue';
import { SelectUserPanel, UserTable } from '@/views/system/user/modules/index.js';
import { useState } from '@/hooks/index.js';

defineOptions({
  inheritAttrs: false
});

const props = defineProps({
  api: { type: Function, required: true }
});

const emit = defineEmits(['update:value']);
const value = defineModel('value', { type: Array, default: () => [] });
const [sourceData, setSourceData] = useState([]);
const [openModal, setOpenModal] = useState(false);
const [selectedRowKeys, setSelectedRowKeys] = useState([]);
const [pagination, setPagination] = useState({ pageNum: 1, pageSize: 10 });

const onCancel = (keys = []) => {
  const values = [...toValue(sourceData)].filter(({ key }) => !keys.includes(key));
  emit(
    'update:value',
    values.map(({ key }) => key)
  );
  setSourceData(values);
};

/**
 * 选择完成
 *
 * @param keys
 * @param rows
 */
const onSelectFinish = (keys, rows) => {
  emit('update:value', [...toValue(value), ...keys]);
  setSourceData((v) => [...v, ...rows]);
  setOpenModal(false);
};
</script>

<style lang="scss" scoped>
.page-table-container {
  padding: 0;
}
</style>
